package com.ljf.game.event;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ljf.game.WebsocketManager;
import com.ljf.game.schedule.HeartBeatSchedule;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述 :
 * <p>
 * {
 * "EVENT_CLASS":"JOIN_ROOM",
 * "HOME_OWNER":"admin"
 * }
 * <p>
 * 版本     作者     时间      内容
 * 1.0      lijinfeng       2025-04-29 14:32     create
 */
public class JoinRoomEvent extends AbstractEvent {

    public void run(WebSocketSession session, String text) {

        HashMap<String, Object> hashMap = EventManager.getResultMap(text);

        String username = WebsocketManager.getUsername(session);
        JSONObject jsonObject = JSON.parseObject(text);
        String homeowner = jsonObject.get("HOME_OWNER").toString();

        ConcurrentHashMap<String, WebSocketSession> roomMap = WebsocketManager.groupGet(homeowner);
        // 房间不存在
        if (null == roomMap || roomMap.isEmpty()) {
            WebsocketManager.sendMessage(session, hashMap, "房间 [" + homeowner + "] 不存在");
            return;
        }
        // 房间存在，用户加入
        // 心跳记录
        HeartBeatSchedule.addExistSession(username);
        WebsocketManager.groupAddOne(homeowner, username, session);
        String message = username + " 进入房间";
        WebsocketManager.sendMessageToAll(roomMap, hashMap, message);

    }
}
